<?php
namespace app\index\controller;

use app\common\service\Redis;
use think\Env;
use think\facade\Config;
use think\facade\Session;

class Index extends Init
{
    protected $userModel;
    protected $friendModel;
    protected $userGroupModel;

    public function initialize(){
        parent::initialize();
        $this->userModel = model('common/user');
        $this->friendModel = model('common/friend');
        $this->userGroupModel = model('common/userGroup');
    }

    public function index()
    {
        return $this->fetch('index/index');
    }

    public function init_json(){
        $user_id = session('user_id');
        $init['mine'] = $this->userModel->findUserById($user_id)->toArray();
        $init['mine']['status'] = 'online';
        $friends = $this->friendModel->getFriendDetail($user_id)->toArray();

        $friendData = [];
        $friendData[0]['groupname'] = '在线好友';
        $friendData[0]['id'] = '0';
        $online = $this->userModel->getAllUserExceptMe($user_id);
        foreach ($online as $v){
            $friendData[0]['list'][] = [
                'id'=>$v['id'],
                'username'=>$v['username'],
                'avatar'=>$v['avatar'],
                'sign'=>$v['sign'],
                'status'=>$v['status']== 1?'online':'offline',
                'temporary'=>$v['temporary']== 1?true:false,
            ];
        }
        foreach ($friends as $friend){
            if(!isset($friendData[$friend['group_id']])){
                $friendData[$friend['group_id']]['groupname'] = $friend['groupname'];
                $friendData[$friend['group_id']]['id'] = $friend['group_id'];

            }
            $friendData[$friend['group_id']]['list'][] = [
                'id'=>$friend['id'],
                'username'=>$friend['username'],
                'avatar'=>$friend['avatar'],
                'sign'=>$friend['sign'],
                'status'=>$friend['status'] == 1?'online':'offline',
            ];
        }
        $init['friend'] = $friendData;

        $init['group'] = $this->userGroupModel->getUserGroup($user_id)->toArray();

        $redis = new Redis();
        $redis->set('init_json:'.$user_id,json_encode($init));

        return json(['code'=>0,'msg'=>'','data'=>$init]);
    }

    public function getMembers(){
        $group_id = $this->request->param('id',0);
        if($group_id == 0){
            return ['code'=>-1,'msg'=>'群组不存在'];
        }

        $group_members = $this->userGroupModel->getMembers($group_id);
        $list = [];
        foreach ($group_members as $member){
            $list[] = $member->toArray();
        }

        return json(['code'=>0,'msg'=>0,'data'=>['list'=>$list]]);
    }

    public function uploadImg(){
        $file = $this->request->file('image');
        $env = new Env();
        $root_path = $env->get('root_path');
        $path = $root_path.'uploads/images/';
        $info = $file->move($path);
        if ($info) {
            $result = [
                'code'     => 0,
                'msg'      => '上传成功',
                'data' => ['src'=>$path . str_replace('\\', '/', $info->getSaveName())]
            ];
        } else {
            $result = [
                'code' => -1,
                'msg'  => $file->getError()
            ];
        }
        return json($result);
    }

    public function uploadFile(){
        $file = $this->request->file('file');
        $env = new Env();
        $root_path = $env->get('root_path');
        $path = $root_path.'uploads/file/';
        $info = $file->move($path);
        if ($info) {
            $result = [
                'code'     => 0,
                'msg'      => '上传成功',
                'data' => ['src'=>$path . str_replace('\\', '/', $info->getSaveName()),'name'=>$_FILES['file']['name']]
            ];
        } else {
            $result = [
                'code' => -1,
                'msg'  => $file->getError()
            ];
        }
        return json($result);
    }

    public function getChatLog(){
        $user_id = session('user_id');
        if(!$user_id){
            return json(['code'=>-1,'message'=>'请先登录','data'=>'']);
        }
        $redis = new Redis();
        $data_json = $redis->get('init_json:'.$user_id);
        $data = json_decode($data_json , true);
        $unread_friend = $redis->hGetAll('unread_friend_' . $user_id);
        $friend_chatlog = [];
        if(isset($data['friend'][0])){
            foreach ($data['friend'][0]['list'] as $list){
                $count = isset($unread_friend[$list['id']])?$unread_friend[$list['id']]:0;
                if($count>0){
                    if($count > 99){
                        $count = 99;
                    }
                    $keyName = 'rec:friend:'.getRecKeyName($user_id,$list['id']);
                    $length = $redis->lLen($keyName);
                    if($length <= $count){
                        $start = 0;
                    }else{
                        $start = $length - $count;
                    }
                    $friend_chatlog[$list['id']] =  $redis -> lRange($keyName, (int)($start), -1);
                }
            }
        }else{
            foreach ($data['friend'] as $friend){
                foreach ($friend['list'] as $list){
                    $count = isset($unread_friend[$list['id']])?$unread_friend[$list['id']]:0;
                    if($count>0){
                        if($count > 99){
                            $count = 99;
                        }
                        $keyName = 'rec:friend:'.getRecKeyName($user_id,$list['id']);
                        $length = $redis->lLen($keyName);
                        if($length <= $count){
                            $start = 0;
                        }else{
                            $start = $length - $count;
                        }
                        $friend_chatlog[$list['id']] =  $redis -> lRange($keyName, (int)($start), -1);
                    }
                }
            }
        }

        $group_chatlog = [];
        $group_chatlog_count = [];
        if(isset($data['group'])){
            foreach ($data['group'] as $group){
                $group_time = $redis->get('unread_group_' .$group['id'].'_'. $user_id);
                if(!$group_time){
                    $group_time = time()-86400;
                }
                $group_chatlog_count[$group['id']] = $redis->zCount('rec:group:'.$group['id'],$group_time,time());
                if($group_chatlog_count[$group['id']] > 99){
                    $group_chatlog_count[$group['id']] = 99;
                    $group_time = time()-86400;
                }
                $group_chatlog[$group['id']] = $redis->zRangeByScore('rec:group:'.$group['id'],$group_time,time());
            }
        }
        return json(['code'=>0,'msg'=>'','data'=>[
            'friend_chatlog_count'=>$unread_friend,
            'friend_chatlog'=>$friend_chatlog,
            'group_chatlog_count'=>$group_chatlog_count,
            'group_chatlog'=>$group_chatlog,
        ]]);
    }

    public function setAlreadyRead(){
        $user_id = session('user_id');
        if(!$user_id){
            return json(['code'=>-1,'message'=>'请先登录','data'=>'']);
        }
        $type = $this->request->post('type','');
        $to_id = $this->request->post('to_id',0);
        if(!in_array($type,['friend','group'])){
            return json(['code'=>-2,'message'=>'类型不对','data'=>'']);
        }
        $redis = new Redis();
        if($type == 'friend'){
            $ret = $redis->hDel('unread_friend_' . $user_id,$to_id);
        }else{
            $ret = $redis->set('unread_group_' .$to_id.'_'. $user_id,time());
        }

        if($ret){
            return json(['code'=>1,'message'=>'清除未读消息成功','data'=>'']);
        }
        return json(['code'=>-3,'message'=>'清除未读消息失败','data'=>'']);
    }
}
